#!/usr/bin/env node

import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * 测试脚本 - 通过MCP服务器搜索并显示Java类源码
 * 使用方式: node test-class-search.mjs <className>
 */

// 获取命令行参数
const className = process.argv[2];

if (!className) {
    console.log('使用方式: node test-class-search.mjs <className>');
    console.log('示例: node test-class-search.mjs ExpandDomain');
    process.exit(1);
}

console.log(`🔍 正在搜索类: ${className}`);
console.log(`📁 使用配置文件中的Maven仓库路径`);
console.log('=' + '='.repeat(60));

// MCP请求模拟
const mcpRequest = {
    jsonrpc: "2.0",
    id: 1,
    method: "tools/call",
    params: {
        name: "find_class_in_local_repository",
        arguments: {
            className: className
        }
    }
};

// 启动MCP服务器进程
const serverProcess = spawn('node', ['dist/index.js'], {
    cwd: __dirname,
    stdio: ['pipe', 'pipe', 'inherit'] // stdin, stdout, stderr
});

let output = '';
let hasReceived = false;

// 处理服务器输出
serverProcess.stdout.on('data', (data) => {
    const chunk = data.toString();
    output += chunk;
    
    // 检查是否收到完整的JSON响应
    try {
        // 尝试解析累积的输出
        const lines = output.split('\n').filter(line => line.trim());
        for (const line of lines) {
            if (line.startsWith('{') && !hasReceived) {
                const response = JSON.parse(line);
                if (response.result && response.result.content) {
                    hasReceived = true;
                    handleResponse(response);
                    serverProcess.kill();
                    return;
                }
            }
        }
    } catch (e) {
        // 继续等待更多数据
    }
});

// 发送请求到服务器
serverProcess.stdin.write(JSON.stringify(mcpRequest) + '\n');

// 设置超时
const timeout = setTimeout(() => {
    console.log('❌ 请求超时 (30秒)');
    console.log('💡 请确保服务器正确编译: npm run build');
    serverProcess.kill();
    process.exit(1);
}, 30000);

// 处理响应
function handleResponse(response) {
    clearTimeout(timeout);
    
    try {
        const result = JSON.parse(response.result.content[0].text);
        
        console.log(`📊 搜索结果统计:`);
        console.log(`   - 扫描的artifact数量: ${result.totalArtifactsScanned}`);
        console.log(`   - 找到的匹配类数量: ${result.matchesFound}`);
        console.log(`   - 仓库路径: ${result.repositoryPath}`);
        console.log('');
        
        if (result.classes && result.classes.length > 0) {
            result.classes.forEach((classInfo, index) => {
                console.log(`🎯 类 ${index + 1}: ${classInfo.fullName}`);
                console.log(`   📦 所在artifact: ${classInfo.artifact.groupId}:${classInfo.artifact.artifactId}:${classInfo.artifact.version}`);
                console.log(`   📂 文件路径: ${classInfo.artifact.localPath}`);
                console.log(`   ✅ 反编译状态: ${classInfo.decompiled ? '成功' : '失败'}`);
                console.log('');
                
                if (classInfo.decompiled && classInfo.source) {
                    console.log(`📄 源代码:`);
                    console.log('-'.repeat(80));
                    console.log(classInfo.source);
                    console.log('-'.repeat(80));
                } else {
                    console.log(`❌ 反编译失败: ${classInfo.source}`);
                }
                console.log('');
            });
        } else {
            console.log(`❌ 未找到包含 "${className}" 的类`);
            console.log('💡 提示:');
            console.log('   - 检查类名拼写是否正确');
            console.log('   - 类名支持部分匹配，可以只输入类名的一部分');
            console.log('   - 确保Maven仓库路径配置正确');
        }
        
    } catch (error) {
        console.log('❌ 解析响应失败:', error.message);
        console.log('原始响应:', response.result.content[0].text);
    }
}

// 处理进程错误
serverProcess.on('error', (error) => {
    clearTimeout(timeout);
    console.log('❌ 启动MCP服务器失败:', error.message);
    console.log('💡 请先运行: npm run build');
});

serverProcess.on('exit', (code) => {
    if (code !== 0 && !hasReceived) {
        console.log(`❌ MCP服务器异常退出，代码: ${code}`);
    }
});